import { Body, Controller, Get, Patch, Post, Req, Res, UseGuards } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { Response } from 'express'
import {
  ForgotPasswordDto,
  LoginDto,
  RegisterDto,
  ResetPasswordDto,
  UpdateProfileDto,
} from '../dto/auth.dto'
import { AuthService } from '../services/auth/AuthService'

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  // 微信登录
  @Get('wechat')
  @UseGuards(AuthGuard('wechat'))
  async wechatLogin() {
    // 重定向到微信认证页面
  }

  @Get('wechat/callback')
  @UseGuards(AuthGuard('wechat'))
  async wechatCallback(@Req() req, @Res() res: Response) {
    const user = req.user
    const token = await this.authService.generateToken(user)
    res.redirect(`/?token=${token}`)
  }

  // 手机号/邮箱注册
  @Post('register')
  async register(@Body() registerDto: RegisterDto) {
    return this.authService.register(registerDto)
  }

  // 登录
  @Post('login')
  async login(@Body() loginDto: LoginDto) {
    return this.authService.login(loginDto)
  }

  // 密码找回
  @Post('forgot-password')
  async forgotPassword(@Body() forgotPasswordDto: ForgotPasswordDto) {
    return this.authService.sendResetPasswordEmail(forgotPasswordDto.email)
  }

  // 重置密码
  @Patch('reset-password')
  async resetPassword(@Body() resetPasswordDto: ResetPasswordDto) {
    return this.authService.resetPassword(resetPasswordDto.token, resetPasswordDto.newPassword)
  }

  // 获取用户信息
  @Get('profile')
  @UseGuards(AuthGuard('jwt'))
  async getProfile(@Req() req) {
    return this.authService.getProfile(req.user.id)
  }

  // 更新用户信息
  @Patch('profile')
  @UseGuards(AuthGuard('jwt'))
  async updateProfile(@Req() req, @Body() updateProfileDto: UpdateProfileDto) {
    return this.authService.updateProfile(req.user.id, updateProfileDto)
  }
}
